import re
import pkg_resources

from trac.core import *
from trac.web.chrome import ITemplateProvider
from trac.web.main import IRequestHandler
from trac.perm import IPermissionRequestor
from trac.util import escape, Markup
from trac.core import Component, implements
from trac.ticket import model
from trac.core import TracError
from trac.ticket.model import Ticket
from trac.ticket.web_ui import TicketModule
from trac.ticket.api import TicketSystem

class EmbeddingSystem(Component):
    implements(IRequestHandler, IPermissionRequestor, ITemplateProvider)

    # IPermissionRequestor method
    def get_permission_actions(self):
        return ['TICKET_MODIFY']
        # maybe some other privilege names


    # IRequestHandler methods
    def match_request(self, req):
        match = re.match(r'/api/ticket/([0-9]+)$', req.path_info)
        if match:
            req.args['id'] = match.group(1)

        # ticked_id = req.args.get('id')
        # print self.env
        # print req.path_info

        return True

    def process_request(self, req):

        # env = trac.env.Environment("bloodhound/environments/main")
        # print self.env.path

        ticket_id = req.args.get('id')

        # print "PROCESS_REQUEST"
        # print ticket_id
        # print req.path_info
        # print self.env

        data = {'ticket': Ticket(self.env, ticket_id)}
        return 'ticket.html', data, None


    ### ITemplateProvider methods

    def get_templates_dirs(self):
        resource_filename = pkg_resources.resource_filename
        return [resource_filename('bhembedding', 'templates')]

    def get_htdocs_dirs(self):
        return [] # temporarily, since there are no html docs yet
        # from pkg_resources import resource_filename
        # return [('ticket', resource_filename('bhembedding', 'htdocs'))]
